<template>
  <el-dialog
    width="500px"
    v-bind="$attrs"
    @close="handleClose"
    @open="handleOpen"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      size="small"
      @submit.prevent.native
    >
      <el-form-item :label="$t('system.ram.app_name')" prop="name">
        <el-input
          v-model="form.name"
          maxlength="32"
          show-word-limit
          :placeholder="$t('system.ram.enter_app_name')"
          @blur="() => (form.name = form.name.trim())"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="small" @click="handleClose">{{
          $t('common.cancel')
        }}</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="confirmLoading"
          @click="handleConfirm"
        >
          {{ $t('common.confirm') }}
        </el-button>
      </span></template
    >
  </el-dialog>
</template>

<script>
import { editUserName, getUser } from '@/api/user'

export default {
  props: ['userId', 'name'],
  data() {
    return {
      confirmLoading: false,
      form: {
        name: '',
        status: '0',
        userId: null,
        orgId: '',
        userType: 2,
        countryCode: '',
        roleList: [],
        remark: '',
        storeUuid: ''
      },
      orgId: '',
      countryCode: '',
      rules: {
        name: [
          {
            required: true,
            message: this.$t('system.ram.validate_require'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    getEditUserInfo(userId) {
      getUser(userId)
        .then((res) => {
          this.form.userId = res.userId
          this.form.orgId = res.orgId
          this.form.storeUuid = res.storeUuid
          this.form.remark = res.remark
          this.form.countryCode = res.countryCode
          this.form.status = res.status
          this.form.roleList = res.roleList
        })
        .catch(this.$confirmError)
    },
    handleOpen() {
      this.form.name = this.name
      this.getEditUserInfo(this.userId)
    },
    handleConfirm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.confirmLoading = true
          editUserName(this.userId, this.form)
            .then((res) => {
              this.confirmLoading = false
              this.$message.success(this.$t('system.ram.edit_success'))
              this.$emit('submit')
              this.handleClose()
            })
            .catch((e) => {
              this.confirmLoading = false
              this.$confirmError(e)
            })
        }
      })
    },
    handleClose() {
      this.confirmLoading = false
      this.$refs['form'].clearValidate()
      this.$emit('update:model-value', false)
    }
  }
}
</script>

<style>
</style>
